package com.sf.marathon.soul.core.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.google.common.collect.Lists;
import com.sf.marathon.soul.core.base.ContentTypes;
import com.sf.marathon.soul.core.web.CustomizeFastJsonHttpMessageConverter;

/**
 * web 工程 Bean 相关配置<br>
 *
 * @author liutao<br>
 * @since 2017年9月28日上午9:48:21<br>
 */
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    private RestTemplateBuilder builder;

    /**
     * 使用fastjson作为httpMessage转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        addMessageConverters(converters);
    }

    private void addMessageConverters(List<HttpMessageConverter<?>> converters) {
        if (converters == null) {
            converters = Lists.newArrayList();
        }
        List<MediaType> mediaTypeList = new ArrayList<>();
        mediaTypeList.add(MediaType.valueOf(ContentTypes.TEXT_HTML_UTF8));
        mediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);

        CustomizeFastJsonHttpMessageConverter fastConverter = new CustomizeFastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        // 不能使用该配置，会导致所有的日期都返回该格式，尽管vo上指定了JSONField，不同的日期格式
//		fastJsonConfig.setDateFormat(DateFormats.DF1_16);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        fastConverter.setSupportedMediaTypes(mediaTypeList);
        converters.add(fastConverter);
    }

}
